package cn.jhc.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.jhc.bean.UserBean;
import cn.jhc.dao.ConnectionFactory;
import cn.jhc.dao.TitleDAO;

@WebServlet(name="loginuser",urlPatterns={"/loginaction.do"},loadOnStartup=1)
public class loginActionServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/plain;charset=utf8");
		String getb =req.getParameter("getb");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String id =req.getParameter("id");
		String yzm = req.getParameter("yzm");
		HttpSession session = req.getSession();
		String stryzm=(String)session.getAttribute("ImageServlet"); 
		String s = req.getParameter("rememberusername");
		int remember = s != null ? Integer.valueOf(s) : 0;
		if(remember == 1) {
			Cookie cookie = new Cookie("username",username);
			resp.addCookie(cookie);
		}
		if(yzm!=null&&stryzm!=null){
			 yzm=yzm.toUpperCase();
		       if(!yzm.equals(stryzm)){
		    	   req.getRequestDispatcher("/login.jsp").forward(req, resp);
		       }else{
		    	   TitleDAO dao = new TitleDAO();
		    	   dao.setCon(ConnectionFactory.getConnection());
		    	   UserBean user = dao.findUser(username, password);
		   			if(user==null) {
		   				req.getRequestDispatcher("/login.jsp").forward(req, resp);
		   			}
		   			else {
		   				session.setAttribute("user", user);
		   				req.setAttribute("id", id);
		   				RequestDispatcher dispatcher = req.getRequestDispatcher(getb);
		   				dispatcher.forward(req, resp);
		   			}
		      }
		}
		
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

}
